<template>
	<view>
		<chat-message-navbar :name="chat.name"></chat-message-navbar>
		<!-- <cu-custom bgColor="bg-gradual-pink" :isBack="true"><block slot="backText">返回</block><block slot="content">聊天</block></cu-custom> -->
		<scroll-view :style="{height:height+'px'}" scroll-y :show-scrollbar="true" :scroll-with-animation="true">
			<view class="cu-chat" style="padding-top: 10rpx;">
				<block v-for="(message,index) in allMessage" :key="index">
					<!-- 时间显示 -->
					<!-- <view class="date">2018年3月23日 13:23</view> -->
					<view class="cu-item" :class="{'self':message.isMe}">
						<!-- 是本人，则先显示消息再显示头像 -->
						<block v-if="message.isMe==true||message.isMe=='true'">
							<view class="main">
								<view class="content shadow bg-green" style="display: block;">
									<image v-if="message.type=='image'" :src="message.content" mode="widthFix"></image>
									<view v-else>{{message.content}}</view>
								</view>
							</view>
							<view class="cu-avatar radius" :style="{'background-image':'url('+myAvatar+')'}">
							</view>
						</block>
						<block v-else>
							<view class="cu-avatar radius" :style="{'background-image':'url('+chat.avatar+')'}">
							</view>
							<!-- 不是本人部分，先显示头像再显示消息 -->
							<view class="main">
								<view class="content shadow" style="display: block;">
									<image v-if="message.type=='image'" :src="message.content" mode="widthFix"></image>
									<view v-else>{{message.content}}</view>
								</view>
							</view>
						</block>
					</view>
				</block>
			</view>
		</scroll-view>
		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view>
			<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
				@focus="InputFocus" @blur="InputBlur" v-model="nowMessage"></input>
			<view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<button @click="submit" class="cu-btn bg-green shadow">发送</button>
		</view>
	</view>
</template>

<script>
	import chatNavbar from "../chat-navbar.vue";
	import chatMessageNavbar from "./chat-message-navbar.vue";
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	export default {
		computed: mapState(['isLogin', 'loginUserInfo']),
		components: {
			chatMessageNavbar
		},
		onLoad(options) {
			this.chat = JSON.parse(decodeURIComponent(options.item));
			// console.log(this.chat)
			this.myAvatar = this.loginUserInfo.avatar
			this.tableName = "m" + this.chat.userId
			// console.log(this.tableName)
			//创建数据表，如果存在，则创建失败(创建数据库放在)
			this.$mySqlite.createChat(this.tableName, res => {
				// console.log(res)
			})
			this.$mySqlite.openComDB(this.loginUserInfo.id, {})
			this.loadAllMsg();
			//如果当前没有未读消息，则加载20条历史记录
			if (this.allMessage.length == 0) {
				this.loadOldMsg(this.MAX_INTEGER, 20);
			}
		},
		data() {
			return {
				height: this.swiperHeight-52,
				myAvatar: "",
				InputBottom: 0,
				nowMessage: "",
				tableName: "m1171702529",
				allMessage: [],
				chat: {
					userId: "", //用户id
					name: "", //用户名
					userTag: "", //名字后面的标签，标签为好友的设置
					isOnLine: true, // 是否在线
					avatar: "", //用户头像
					latelyMsg: "", //最近的一条消息
					latelyTime: "22:20", //最新消息的时间
					unreadNum: 100, //未读消息数
					unreadMsg: [], //未读消息列表
					isSuccess: false, //消息是否发送成功
					isDoNotDisturb: true, //是否勿扰 勿扰则未读消息个数消息显示为灰色
				}
			};
		},
		methods: {
			...mapMutations(['resetlatelyMsg']),
			loadAllMsg() {
				//取出缓存数据
				this.allMessage = this.chat.unreadMsg;
				//缓存清空
				//如果当前未读消息大于缓存中的未读消息，则右侧显示一个标志，查看剩余未读消息xxx条。
			},
			loadRemainUnreadMsg() {
				var num = this.chat.unreadNum - this.allMessage.length;
				//加载数据库中最后的num条数据
				this.loadOldMsg(this.MAX_INTEGER, num);
			},
			/**
			 * @param {Object} nowMsgId 如果当前消息记录为空，则第一次获取的nowMsgId为this.MAX_INTEGER;
			 * @param {Object} pageNum 获取历史记录一次默认为20
			 */
			loadOldMsg(nowMsgId, pageNum) {
				//消息的id为消息在历史记录中的第几位
				this.$mySqlite.getOldMsg(this.tableName, nowMsgId, pageNum, res => {
					if (res.status == this.$myEnum.status.WARNING) {
						console.log("没有历史数据了")
					} else {
						var data = res.data
						for (var i = 0; i < data.length; i++) {
							data[i].time = this.getTime(data[i].time)
							this.allMessage.push(data[i])
						}
						// console.log(this.allMessage)
					}
					// console.log(res)
				})
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			submit() {
				var that = this;
				//消息存入本地sqlite数据库
				// var msg = {
				// 	content:this.nowMessage,
				// 	type:"TEXT",
				// 	time:new Date().getTime(),
				// 	isMe:1,
				// }
				var msg = that.$myEntity.Msg(that.nowMessage, that.$myEnum.type.TEXT, null)
				console.log(msg)
				var dataContent = that.$myEntity.MsgContent(that.$myEnum.action.CHAT,that.loginUserInfo.id,that.chat.userId,msg,null)
				var data = JSON.stringify(dataContent)
				console.log(dataContent)
				that.$mySqlite.insertMsg(that.tableName, msg, res => {
					console.log(res)
					if(res.status==this.$myEnum.status.SUCCESS){
						// console.log(data)
						uni.sendSocketMessage({
						  data: data,
						  complete(q) {
							  //发送成功后，服务器需要返回可靠字段
							console.log(q)
						  }
						});
						//刷新消息
						// this.loadAllMsg()
						//插入后，放入消息记录sqlite中，并存入当前展示队列中，更改当前缓存的最新消息！
						that.nowMessage = ""
					}
				})
				console.log(that.allMessage)
				//最新消息放入缓存
				console.log(msg)
				msg.time = this.getTime(msg.time)
				that.resetlatelyMsg({
					userId: that.chat.userId,
					msg: msg
				})
				that.allMessage.push(msg)
			},
			getTime(time){
				time = new Date(time)
				time = time.getHours() + ":" + time.getMinutes()
				return time
			}
		}
	}
</script>

<style>
	page {
		padding-bottom: 100upx;
	}

	.date {
		font-size: 24upx;
		color: #8799a3;
		text-align: center;
	}
</style>
